package com.xyhy.starter.redis;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.SerializationException;
import org.springframework.data.redis.serializer.RedisSerializer;

import com.xyhy.core.jackson.JacksonMapper;

import lombok.SneakyThrows;

public class JsonRedisSerializer<T> implements RedisSerializer<T> {
  private Class<T> type;

  public JsonRedisSerializer(Class<T> type) {
    this.type = type;
  }

  @Override
  @SneakyThrows
  public byte[] serialize(T t) throws SerializationException {
    return JacksonMapper.instance.objectMapper.writeValueAsBytes(t);
  }

  @Override
  @SneakyThrows
  public T deserialize(byte[] bytes) throws SerializationException {
    if (ArrayUtils.isEmpty(bytes)) {
      return null;
    }

    return JacksonMapper.instance.objectMapper.readValue(bytes, type);
  }
}
